//
//  CodeView.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/25.
//

import UIKit
import SVProgressHUD

enum CodeVCType {
    case setting
    case input
    case close
    case pwdTips
}

import UIKit
import SVProgressHUD

protocol CodeViewDeleagate: class
{
    func codeViewUnlock()
    func codeViewClose()
}

class CodeView: UIView
{
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var tf0: UITextField!
    @IBOutlet weak var tf1: UITextField!
    @IBOutlet weak var tf2: UITextField!
    @IBOutlet weak var tf3: UITextField!
    @IBOutlet weak var nextBtn: UIButton!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var closeBtn: UIButton!
    @IBOutlet weak var pwdTipsTextField: UITextField!
    @IBOutlet weak var forgetLabel: UILabel!
    @IBOutlet weak var forgetBtn: UIButton!
    
    var codeString = ""
    var codeSecondString = ""
    var showKeyboard = true
    
    var codeType: CodeVCType!
    {
        didSet
        {
            switch codeType
            {
            case .setting:
                break
            case .input:
                titleLabel.text = "请确认解锁密码"
                nextBtn.setTitle("完成", for: .normal)
                closeBtn.isHidden = true
                
                //忘记了密码
                if let tipsString = UserDefaults.standard.value(forKey: "codeStringTips") as? String {
                    
                    if tipsString.count>0{
                        forgetLabel.isHidden = false
                        forgetBtn.isHidden = false
                        forgetBtn.setTitle("", for: .normal)
                    }else{
                        forgetLabel.isHidden = true
                        forgetBtn.isHidden = true
                    }
                }
                break
            case .close:
                titleLabel.text = "请确认解锁密码"
                nextBtn.setTitle("关闭", for: .normal)
                break
            case .pwdTips:
                titleLabel.text = "设置密码提示"
                nextBtn.setTitle("完成", for: .normal)
            default:
                break
            }
        }
    }
    weak var delegate: CodeViewDeleagate?
    
    
    override init(frame: CGRect)
    {
        super.init(frame: frame)

        setupView()
    }
    
    required init?(coder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        
//        if showKeyboard
//        {
//            tf0.becomeFirstResponder()
//        }
//        self.nextBtn.isHidden = true
    }
    
    override func removeFromSuperview() {
        super.removeFromSuperview()
        
        tf0.resignFirstResponder()
        tf1.resignFirstResponder()
        tf2.resignFirstResponder()
        tf3.resignFirstResponder()
        
    }
    
    func setupView()
    {
        Bundle.main.loadNibNamed("CodeView", owner: self, options: nil)
        addSubview(contentView)
        
        contentView.frame = self.frame
        
//        let blur = UIBlurEffect(style: .light)
//        let blurView = UIVisualEffectView(effect: blur)
//        blurView.alpha = 0.8
//        blurView.frame = CGRect(x: 0, y: 0, width: screen_width, height: screen_height)
//        insertSubview(blurView, at: 0)
        
        tf0.delegate = self
        tf1.delegate = self
        tf2.delegate = self
        tf3.delegate = self

        createTFBorder(tf0)
        createTFBorder(tf1)
        createTFBorder(tf2)
        createTFBorder(tf3)
        
    }
    
    func resetCodeView()
    {
        tf0.text = ""
        tf1.text = ""
        tf2.text = ""
        tf3.text = ""
        
        showKeyboard = true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    {
        endEditing(true)
    }
    
    func createTFBorder(_ forView: UIView)
    {
        forView.layer.cornerRadius = 12.0
        forView.layer.borderWidth = 1.0
        forView.layer.borderColor = UIColor.hexColor(hex: "#C3C3C3").cgColor
    }
}

extension CodeView
{
    @IBAction func forgetBtnAction(_ sender: Any) {
        
        //忘记了密码
        if let tipsString = UserDefaults.standard.value(forKey: "codeStringTips") as? String {
            
            let alertC = UIAlertController.init(title: "密码提示", message: tipsString, preferredStyle: .alert)
            let alertAction = UIAlertAction.init(title: "确定", style: .default) { (action: UIAlertAction) in
                
                alertC.dismiss(animated: true, completion: nil)
            }
            alertC.addAction(alertAction)
            UIApplication.shared.keyWindow?.rootViewController?.present(alertC, animated: true, completion: nil)
            
        }
        
    }
    @IBAction func nextAction(_ sender: Any)
    { //codeString
        endEditing(true)
        
        switch codeType
        {
        case .setting:
            
            //检查是否是设置密码提示
            if pwdTipsTextField.isHidden == false{
                
                
                if let str = pwdTipsTextField.text {
                    
                    if str.count > 0{
                        
                        UserDefaults.standard.setValue(str, forKey: "codeStringTips")

                    }else{
                        
                        SVProgressHUD.showError(withStatus: "提示语必须填写！")
                        SVProgressHUD.dismiss(withDelay: 1)
                        {
                            
                        }
                        UserDefaults.standard.setValue(nil, forKey: "codeStringTips")
                        return
                    }
                }
                
                //保存密码
                UserDefaults.standard.setValue(codeString, forKey: "codeString")
                UserDefaults.standard.synchronize()
                
                // 友盟功能统计
                MobClick.event("function_num", attributes: ["PIN":"开启PIN"])
                
                SVProgressHUD.showSuccess(withStatus: "设置成功")
                SVProgressHUD.dismiss(withDelay: 1.5)
                {
                    self.removeFromSuperview()
                }
                
                return
            }
            
            if codeString.count == 4
            {
                codeSecondString = tf0.text! + tf1.text! + tf2.text! + tf3.text!
            }
            else
            {
//                输入确认密码
                codeString = tf0.text! + tf1.text! + tf2.text! + tf3.text!
                
                tf0.text = ""
                tf1.text = ""
                tf2.text = ""
                tf3.text = ""
                
                tf0.becomeFirstResponder()
                
                titleLabel.text = "请确认解锁密码"
                nextBtn.setTitle("下一步", for: .normal)
                
                return
            }
            
            if codeString == codeSecondString
            {
                tf0.isHidden = true
                tf1.isHidden = true
                tf2.isHidden = true
                tf3.isHidden = true
                pwdTipsTextField.isHidden = false
                nextBtn.isHidden = false
                pwdTipsTextField.becomeFirstResponder()
                titleLabel.text = "设置密码提示"
                nextBtn.setTitle("完成", for: .normal)
                
            }
            else
            {
                SVProgressHUD.showError(withStatus: "两次输入的密码不一致, 请重新输入")
                SVProgressHUD.dismiss(withDelay: 2.0)
                
                codeString = ""
                codeSecondString = ""
                
                tf0.text = ""
                tf1.text = ""
                tf2.text = ""
                tf3.text = ""
                
                titleLabel.text = "请输入解锁密码"
                nextBtn.setTitle("下一步", for: .normal)
                
                tf0.becomeFirstResponder()
            }
            
        case .input:
            
            guard let codeString = UserDefaults.standard.object(forKey: "codeString") as? String else { return }
            
            codeSecondString = tf0.text! + tf1.text! + tf2.text! + tf3.text!
            
            // 解锁
            if codeString == codeSecondString
            {
                delegate?.codeViewUnlock()
                self.removeFromSuperview()
                NotificationCenter.default.post(name: Notification.Name("passView"), object: nil)
            }
            else
            {
                SVProgressHUD.showError(withStatus: "密码不正确")
                SVProgressHUD.dismiss(withDelay: 1.5)
                {
                    self.tf0.becomeFirstResponder()
                }
                
                codeSecondString = ""
                
                tf0.text = ""
                tf1.text = ""
                tf2.text = ""
                tf3.text = ""
            }
            
        case .close:
            
            guard let codeString = UserDefaults.standard.object(forKey: "codeString") as? String else { return }
            
            codeSecondString = tf0.text! + tf1.text! + tf2.text! + tf3.text!
            
            // 关闭
            if codeString == codeSecondString
            {
                UserDefaults.standard.removeObject(forKey: "codeString")
                UserDefaults.standard.synchronize()
                
                // 友盟功能统计
                MobClick.event("function_num", attributes: ["PINMiMaSuo":"关闭密码锁"])
                
                delegate?.codeViewClose()
                SVProgressHUD.showSuccess(withStatus: "关闭密码")
                SVProgressHUD.dismiss(withDelay: 1.5)
                {
                    self.removeFromSuperview()
                }
            }
            else
            {
                SVProgressHUD.showError(withStatus: "密码不正确")
                SVProgressHUD.dismiss(withDelay: 1.5)
                {
                    self.tf0.becomeFirstResponder()
                }
                
                codeSecondString = ""
                
                tf0.text = ""
                tf1.text = ""
                tf2.text = ""
                tf3.text = ""
            }
            
            break
        case .pwdTips:
            
            if let str = pwdTipsTextField.text {
                
                if str.count > 0{
                    
                    UserDefaults.standard.setValue(str, forKey: "codeStringTips")
                    SVProgressHUD.showSuccess(withStatus: "密码提示设置成功")
                    SVProgressHUD.dismiss(withDelay: 1.5)
                    {
                        self.removeFromSuperview()
                    }
                }else{
                    
                    SVProgressHUD.showSuccess(withStatus: "密码提示设置成功")
                    SVProgressHUD.dismiss(withDelay: 1.5)
                    {
                        self.removeFromSuperview()
                    }
                }
            }

            break
        default:
            break
        }
    }
    
    @IBAction func closeAction(_ sender: Any)
    {
        endEditing(true)
        delegate?.codeViewClose()
        self.removeFromSuperview()
    }
}

extension CodeView: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        switch textField
        {
        case tf0:
            tf0.text = string
            if string.count == 1
            {
                tf1.becomeFirstResponder()
            }
        case tf1:
            tf1.text = string
            if string.count == 1
            {
                tf2.becomeFirstResponder()
            }
        case tf2:
            tf2.text = string
            if string.count == 1
            {
                tf3.becomeFirstResponder()
            }
        case tf3:
            tf3.text = string
            if string.count == 1
            {
                endEditing(true)
                self.perform(#selector(nextAction(_:)), with: self.nextBtn, afterDelay: 0.5)
            }
        default:
            break
        }
        
        if tf0.text?.count == 1 && tf1.text?.count == 1 && tf2.text?.count == 1 && tf3.text?.count == 1
        {
            nextBtn.isEnabled = true
        }
        else
        {
            nextBtn.isEnabled = false
        }
        
        return true
    }

}
